import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description mybatis 自动生成数据库相关代码
 * @Param null
 * @Return
 * @Author LSS<liushuisheng>
 * @Date 2019/12/2 17:04
 **/
@Data
public class MybatisCodeGenerator {
    //数据库类型
    private final DbType dbType = DbType.MYSQL;
    //数据库连结信息
    private final String dbUrl = "jdbc:mysql://localhost:3306/druid-master?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true";
    private final String driver = "com.mysql.cj.jdbc.Driver";
    private final String userName = "root";
    private final String password = "root";

    private String basePackage = "com.cloud.dataway";
    private String outputModule = "client-parent/dataway";
    private String outputDir = "D:\\2workspaceSelf\\spring-cloud-study\\client-parent\\dataway\\src\\main\\java\\";
    private String author = "yazhou";
    //数据库表名称
    private String tableName = "t_user";
    //生成的文件名称前缀
    private String beanName = "User";

    public static void main(String[] args) {
        //D:\2workspaceSelf\spring-cloud-study\client-parent\dataway\src\main\java\com\cloud\dataway


        MybatisCodeGenerator mybatisCodeGenerator = new MybatisCodeGenerator();
        mybatisCodeGenerator.generateByTables();
    }
    /**
     * 根据表自动生成
     *
     * @author Terry
     */
    private void generateByTables() {
        //配置数据源
        DataSourceConfig dataSourceConfig = new DataSourceConfig().setDbType(dbType).setUrl(dbUrl).setUsername(userName).setPassword(password).setDriverName(driver);
        // 策略配置
        StrategyConfig strategyConfig = new StrategyConfig()
                // 全局大写命名 ORACLE 注意
                .setCapitalMode(true)
                //从数据库表到文件的命名策略
                .setNaming(NamingStrategy.underline_to_camel)
                //需要生成的的表名，多个表名传数组
                .setInclude(tableName).setEntityLombokModel(true).setRestControllerStyle(true);

        //全局变量配置
        GlobalConfig globalConfig = new GlobalConfig().setBaseColumnList(true).setBaseResultMap(true)
                .setActiveRecord(false).setAuthor(author).setOpen(false)
                .setOutputDir(outputDir).setFileOverride(true)
                .setEntityName(beanName + "Entity")
                .setMapperName(beanName + "Mapper")
                .setXmlName(beanName + "Mapper")
                .setServiceName(beanName + "Service")
                .setServiceImplName(beanName + "ServiceImpl")
                .setControllerName(beanName + "Controller")
                .setEnableCache(false);

        //包名配置
        PackageConfig packageConfig = new PackageConfig().setParent(basePackage)
                .setEntity("entity")
                .setController("controller")
                .setService("service")
                .setServiceImpl("service.impl")
                .setMapper("mapper")
                .setXml("mapper.xml");

        //自定义配置
        //InjectionConfig injectionConfig = getInjectionConfig();
        //模板配置
        TemplateConfig templateConfig = getTemplateConfig();

        //自动生成
        new AutoGenerator()
                .setGlobalConfig(globalConfig)
                .setDataSource(dataSourceConfig)
                .setStrategy(strategyConfig)
                .setPackageInfo(packageConfig)
                //.setCfg(injectionConfig)
                .setTemplate(templateConfig)
                .execute();
    }

    private InjectionConfig getInjectionConfig() {
        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };
        String templatePath = "/templates/mapper.xml.vm";
        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                return outputDir+ basePackage.replaceAll("\\.", "/") + "/mapper/"
                        + tableInfo.getMapperName() + StringPool.DOT_XML;
            }
        });
        cfg.setFileOutConfigList(focList);
        return cfg;
    }

    public TemplateConfig getTemplateConfig() {
        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();
        // 配置自定义输出模板
        //指定自定义模板路径，注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
        // templateConfig.setEntity("templates/entity2.java");
        // templateConfig.setService();
        // templateConfig.setController();
        //不在源代码目录下生成xml文件
        templateConfig.setXml(null);
        //不在源代码目录下生成controller代码
        //templateConfig.setController(null);
        return templateConfig;
    }
}